#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 设定初始模式
    this->client_or_server = ui->comboBox->itemText(ui->comboBox->currentIndex());
    qDebug() << ui->comboBox->itemText(ui->comboBox->currentIndex());

    // 清空输入框的数据
    ui->lineEdit->clear();
    ui->lineEdit_2->clear();
}

Widget::~Widget()
{
    delete ui;
}



void Widget::on_pushButton_2_clicked(bool checked)
{
    if(checked == 1)
    {
        ui->pushButton_2->setText("断开");

    }
    else
    {
        ui->pushButton_2->setText("连接");
        return ;
    }

    // 连接 TCP 客户端
    if(ui->comboBox->itemText(ui->comboBox->currentIndex()) == "TCP客户端")
    {
        qDebug() << "11111";
        // 判断数据是否有效
        // 设定连接参数
        client.set_connect( ui->lineEdit->text() , ui->lineEdit_2->text().toUInt() );

        // tcp连接
        client.start_connect();

        // 连接信号
        connect( &client , &TCP_client::connect_sig , this , [&](){
            qDebug() << "连接成功";
        } );
        connect( &client , &TCP_client::dis_connect_sig , this , [&](){
            qDebug() << "断开连接";
        });
        // 服务器信号
        connect( &client , &TCP_client::read_sig , this , [&](QString message){
            qDebug() << "接收到信息: " <<  message;
            ui->textEdit->setText(ui->textEdit->toPlainText() + message);

        });

    }
    if(ui->comboBox->itemText(ui->comboBox->currentIndex()) == "TCP服务器")
    {
        // 启动监听
        server.listen(ui->lineEdit_2->text().toUInt());

        // 绑定信号
        connect(&this->server , &tcp_server::recv_sig , this , [&](QString smg){
            ui->textEdit->setText(ui->textEdit->toPlainText() + smg);
        });
    }


}

// 选择为 客户端 还是 服务器
void Widget::on_comboBox_currentIndexChanged(const QString &arg1)
{
    this->client_or_server = arg1;
    qDebug() << ui->comboBox->itemText(ui->comboBox->currentIndex());


}

void Widget::on_pushButton_clicked()
{
    // 连接 TCP 客户端
    if(ui->comboBox->itemText(ui->comboBox->currentIndex()) == "TCP客户端")
    {
        // 发送数据
        client.send_msg(ui->lineEdit_3->text());

        ui->textEdit->setText(ui->textEdit->toPlainText() + ui->lineEdit_3->text());
    }
}
